<?php
session_start();
require_once '../config/database.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

// 检查用户登录状态
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => '未登录']);
    exit;
}

$user_id = $_SESSION['user_id'];
$action = $_POST['action'] ?? '';

try {
    if ($action === 'buy') {
        $amount = floatval($_POST['amount'] ?? 0);
        
        if ($amount <= 0) {
            throw new Exception('投注金额必须大于0');
        }
        
        $result = processBuyTransaction($user_id, $amount);
        echo json_encode($result);
        
    } elseif ($action === 'sell') {
        $position_id = intval($_POST['position_id'] ?? 0);
        
        if ($position_id <= 0) {
            throw new Exception('无效的持仓ID');
        }
        
        $result = processSellTransaction($user_id, $position_id);
        echo json_encode($result);
        
    } else {
        throw new Exception('无效的操作');
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
